import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-25
 * Time: 19:36
 */

class Solution {
    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for(String s:strs){
            char[] cur = s.toCharArray();
            Arrays.sort(cur);
            String key = new String(cur);
            //如果key是新值，就new一个数组
            List<String> List = map.getOrDefault(key, new ArrayList<>());
            List.add(s);
            map.put(key,List);
        }
        return new ArrayList<>(map.values());
    }

    /*public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for(String str : strs){
            char[] cur = str.toCharArray();
            Arrays.sort(cur);
            String key = new String(cur);
            if(!map.containsKey(key)){
                map.put(key,new ArrayList<>());
            }
            map.get(key).add(str);
        }
        return new ArrayList<>(map.values());
    }*/

    public static void main(String[] args) {
        String[] strings = new String[]{"abc","abc","bca","x"};
        List<List<String>> arrayLists = groupAnagrams(strings);
        for (List<String> cur : arrayLists) {
            for (String s : cur) {
                System.out.print(s + " ");
            }
            System.out.println();
        }
    }
}
